/**
 * Filter for the columns of type double (number)
 * 
 * @author remo.lemma@lu.unisi.ch
 */

package ch.unisi.inf.projects.java.uom.gui.table.item.filter;

import java.util.ArrayList;
import java.util.List;

import org.jdesktop.swingx.decorator.Filter;

public class NumberFilter extends Filter
{
	private List<Integer> toPrevious;

	private String operator;
	
	private double filter; 
	
	private boolean list;
	
	public NumberFilter (final String operator, final double filter, final boolean list, final int col)
	{
		super(col);
		toPrevious = new ArrayList<Integer>();
		setFilter(operator, filter, list);
	}
	
	public void setFilter (final String operator, final double filter, final boolean list)
	{
		this.operator = operator;
		this.filter = filter;
		this.list = list;
		refresh();
	}
	
	public void init ()
	{
		toPrevious = new ArrayList<Integer>();
	}
	
	public void reset ()
	{
		toPrevious.clear();
		final int inputSize = getInputSize();
		fromPrevious = new int[inputSize];
		for (int i = 0; i < inputSize; i++)
			fromPrevious[i] = -1;
	}
	
	public void filter ()
	{
		final int inputSize = getInputSize();
		int current = 0;
		for (int i = 0; i < inputSize; i++) {
			if (!adapter.isTestable(getColumnIndex()))
				return;
			String s = getInputValue(i, getColumnIndex()).toString();
			if (list)
				s = s.split(" ")[0];
			if (s.equals(""))
				continue;
			try {
				final Double value = Double.parseDouble(s);
				if (((operator.equals(">") || operator.equals(">=")) && value > filter) ||
						((operator.equals("<") || operator.equals("<=")) && value < filter) ||
						((operator.equals("=") || operator.equals(">=") || operator.equals("<=")) && value == filter)) {
						toPrevious.add(new Integer(i));
						fromPrevious[i] = current++;
				}
			}
			catch (final NumberFormatException nfe) {
				continue;
			}
				
		}
	}
	
	public int getSize()
	{
		return toPrevious.size();
	}
	
	protected int mapTowardModel (final int row)
	{
		return toPrevious.get(row);
	}
}